<script setup>
import { ref, reactive, defineEmits, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from '@element-plus/icons-vue';
import axios from "axios";

const categoryList = ref([]);
const consultantList = ref([]);

// 表单数据
let form = reactive({
  courseName: "",
  videoFilename: "",
  image: "",
  originalPrice: "",
  currentPrice: "",
  description: "",
  targetAudience: "",
  learningOutcomes: "",
  subscriptionNotes: "",
  consultantId: "",
  listingTime: "",
  categoryId: "",
  date: ""
});

// 表单验证规则
const rules = ref({
  courseName: [
    { required: true, message: '课程名称不能为空', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '课程简介不能为空', trigger: 'blur' }
  ],
  consultantId: [
    { required: true, message: '请选择咨询师', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ]
});

const imageUrl = ref('');

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  form.image = response;
};

onMounted(async () => {
  try {
    const response = await axios.get('/api/courseCategory/list');
    categoryList.value = response.data.data.list || [];

    const consultantResponse = await axios.get('/api/consultant/listAllConsultant');
    consultantList.value = consultantResponse.data.data || [];
  } catch (error) {
    ElMessage.error('初始化数据失败');
    console.error('初始化失败:', error);
  }
});

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像必须为 JPG 格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 定义 emit
const emit = defineEmits(["addValue"]);

// 表单引用
const formRef = ref();

async function saveAction() {
  // 调用 Element Plus 表单验证
  const valid = await formRef.value.validate();
  if (!valid) {
    ElMessage.warning('请填写必填字段');
    return;
  }

  try {
    const response = await axios.post('/api/course/add', form);
    console.log('保存成功:', response.data);

    ElMessage.success('课程添加成功');

    // 清空表单
    form.courseName = '';
    form.videoFilename = '';
    form.image = '';
    form.originalPrice = '';
    form.currentPrice = '';
    form.description = '';
    form.targetAudience = '';
    form.learningOutcomes = '';
    form.subscriptionNotes = '';
    form.consultantId = '';
    form.listingTime = '';
    form.categoryId = '';
    form.date = '';
    imageUrl.value = '';

    emit("addValue", form);
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('课程添加失败');
  }
}

</script>
<template>
  <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
    <!-- 课程名称 -->
    <el-form-item label="课程名称" prop="courseName">
      <el-input v-model="form.courseName" placeholder="请输入课程名称"></el-input>
    </el-form-item>

    <!-- 视频文件 -->
    <el-form-item label="视频文件">
      <el-input v-model="form.videoFilename" placeholder="请上传课程视频"></el-input>
    </el-form-item>

    <!-- 课程图片 -->
    <el-form-item label="课程图片">
      <el-upload
          class="avatar-uploader"
          action="/api/oss/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <!-- 原价 -->
    <el-form-item label="原价">
      <el-input v-model="form.originalPrice" placeholder="请输入原价"></el-input>
    </el-form-item>

    <!-- 现价 -->
    <el-form-item label="现价">
      <el-input v-model="form.currentPrice" placeholder="请输入现价"></el-input>
    </el-form-item>

    <!-- 课程简介 -->
    <el-form-item label="课程简介" prop="description">
      <el-input v-model="form.description" placeholder="请输入课程简介"></el-input>
    </el-form-item>

    <!-- 适用人群 -->
    <el-form-item label="适用人群">
      <el-input v-model="form.targetAudience" placeholder="请输入适用人群"></el-input>
    </el-form-item>

    <!-- 学习收获 -->
    <el-form-item label="学习收获">
      <el-input v-model="form.learningOutcomes" placeholder="请输入学习收获"></el-input>
    </el-form-item>

    <!-- 订阅须知 -->
    <el-form-item label="订阅须知">
      <el-input v-model="form.subscriptionNotes" placeholder="请输入订阅须知"></el-input>
    </el-form-item>

    <!-- 咨询师 -->
    <el-form-item label="咨询师" prop="consultantId">
      <el-select v-model="form.consultantId" placeholder="请选择咨询师">
        <el-option
            v-for="item in consultantList"
            :key="item.consultantId"
            :label="item.username"
            :value="item.consultantId"
        />
      </el-select>
    </el-form-item>

    <!-- 有效期 -->
    <el-form-item label="有效期">
      <el-input v-model="form.listingTime" placeholder="请输入有效期"></el-input>
    </el-form-item>

    <!-- 课程类别 -->
    <el-form-item label="课程类别" prop="categoryId">
      <el-select v-model="form.categoryId" placeholder="请选择分类">
        <el-option
            v-for="item in categoryList"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
        />
      </el-select>
    </el-form-item>

    <!-- 创建时间 -->
    <el-form-item label="创建时间">
      <el-date-picker
          v-model="form.date"
          type="datetime"
          placeholder="请选择日期"
          size="normal"
          value-format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
  </el-form>

  <div style="display: flex; justify-content: center;">
    <el-button @click="saveAction">保存</el-button>
  </div>
</template>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>
